// 防抖
export function antiShake(fun, options) {
    const baseOptions = Object.assign(
        {
            delay: 200,
        },
        options
    );
    let timer = null;
    return function(...arg) {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fun.apply(this, arg);
        }, baseOptions.delay);
    };
}

export function throttle(fun, options) {
    const baseOptions = Object.assign(
        {
            interval: 16,
        },
        options
    );
    let time = new Date().valueOf();
    let timer = null;
    return function(...arg) {
        const nowTime = new Date().valueOf();
        clearTimeout(timer);
        if (nowTime > time + baseOptions.interval) {
            fun.apply(this, arg);
            time = nowTime;
            return;
        }

        // 执行最后一次
        timer = setTimeout(() => {
            fun.apply(this, arg);
        }, 100);
    };
}

export function AutoUnevent() {
    this.queue = [];
}
AutoUnevent.prototype = {
    constructor: AutoUnevent,
    on(el, eventName, fun, options) {
        const that = this;
        el.addEventListener(eventName, fun, options);
        const remove = () => {
            that.off(el, eventName, fun, options);
            const index = that.queue.indexOf(remove);
            if (index !== -1) {
                that.queue.splice(index, 1);
            }
        };
        this.queue.push(remove);
        return remove;
    },
    off(el, eventName, fun, options) {
        el.removeEventListener(eventName, fun, options);
    },
    clear() {
        if (this.queue.length === 0) {
            return;
        }
        this.queue.forEach(i => i());
        this.queue.length = 0;
    },
};
